import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:music_player/music_player.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class MusicPlayerPage extends StatefulWidget {
  const MusicPlayerPage({Key? key}) : super(key: key);

  @override
  State<MusicPlayerPage> createState() => _MusicPlayerPageState();
}

class _MusicPlayerPageState extends State<MusicPlayerPage> {

  ///实例化音频播放器
  late MusicPlayer audioPlayer;
  bool isSetSuccess = false;
  List<double>? waveData = List.generate(20, (index) => 0);
  int volumeSize=0;
  @override
  void initState() {
    super.initState();

    //请求音频权限
    Permission.audio.request();
    //请求麦克风权限
    Permission.microphone.request();
    //下载音乐
    downloadMusic().then((filePath) async {

      if(filePath!= null){
        //实例化音频播放器
        audioPlayer = MusicPlayer();
        //音频播放器.设置音乐（音乐信息，是否启动FFT）
        audioPlayer.setMusic(MusicInfo(duration: 14000, url: filePath),enableFft: true).then((value) => isSetSuccess = value);
        //音频播放器.设置值回调
        // audioPlayer.setValueCallback(
        // //音乐状态回调
        // MusicStateCallback(
        //   //频谱回调
        //     fftChangeCallback: (data){
        //       setState(() {waveData = data;},);
        //     },
        //     //音量大小回调
        //     visualizerChangeCallback: (data){
        //       setState(() {volumeSize = data;},);
        //     }
        // ),
        // );

      }

    });
    ///https://assist.magichue.net:4473/audioFile/audio/sys/Halloween night music-Witch's dream.mp3
    ///
    ///
    ///
  }

  @override
  void dispose() {
    //音频播放器.暂停()
    audioPlayer.pause();
    //音频播放器.释放()
    audioPlayer.release();
    super.dispose();
  }

  //获取得到视频缓存路径
  Future<String> getVideoCachePath() async {
    //获取申请文件目录
    final Directory dir = await  getApplicationDocumentsDirectory();
    //创建缓存文件
    final Directory cacheDir = Directory(dir.path);
    //实例化音频文件 = 目录('${cacheDir.path}/music');
    Directory videoDir = Directory('${cacheDir.path}/music');
    //视频Dir是如果不存在
    if (!await videoDir.exists()) {
      videoDir = await videoDir.create();
    }
    //返回视频Dir路径
    return videoDir.path;
  }

  Future<String?> downloadMusic() async {
    // String musicPath = 'http://resource.surplife.net/cloud/img/app/Dance Of Fireflies.mp3';
    //网络音频路径
    String musicPath = 'http://resource.surplife.net/cloud/img/app/DemoSong.mp3';
    //字符处理
    var fileName = musicPath.split('/').last;
    try {
      //获取文件缓存地址
      var cachePath = await getVideoCachePath();
      //拼接完整文件路径
      var filePath = '$cachePath/$fileName';
      //获取文件
      var file = File(filePath);
      //如果文件不存在同步
      if(!file.existsSync()){
        var dio = Dio();
        await dio.download(musicPath, filePath, onReceiveProgress: (int count, int total) {
          //获取下载进度百分比
          var downloadProgress = count / total;
          print('download :$downloadProgress');
        },
          //是否错误时删除
          deleteOnError: false,
        );
      }
      //下载完成返回路径
      return filePath;
    } on DioError catch (error) {
      //失败者，捕获Dio异常
      if (error.response?.statusCode == 404) {
        print('下载音乐失败,文件资源不存在！');

      } else {
        print(error.toString());
      }
      return null;
    } catch (error) {
      print(error.toString());
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                    onPressed: () {
                      if(!isSetSuccess) return;
                      audioPlayer.start();
                    },
                    child: Text('Play')),
                ElevatedButton(
                    onPressed: () {
                      if(!isSetSuccess) return;
                      audioPlayer.pause();
                    },
                    child: Text('Pause')),
              ],)
          ],
        ),
      ),
    );
  }
}